from flask import Blueprint, request, Response
from flask_siwadoc import BaseModel, Blueprint
from db_init import db
from swaager_init import siwa
from model.model import Advertise, House, Order, Comment, Facility
from tools.tools import item2dict, my_route, my_cache
from sqlalchemy import text
from flask_login import login_required, current_user


house = siwa.blueprint('house', __name__)


class AddHouse(BaseModel):
    title: str
    info: str
    zheng: bool = True
    p_num: int
    c_num: int
    live: bool = True
    city: str
    price: int


@house.route('/', methods=['post'])
@login_required
def add_house():
    data = request.json
    data['master_id'] = 1
    if 1:
        db.session.add(House(**data))
        db.session.commit()
        return my_route(200)
    return my_route(401)


@house.route('/ad', methods=['GET'])
def ad():
    ads = Advertise.query.filter_by().all()

    for i in range(1000):
        ads = Advertise.query.filter_by().all()
    return my_route(200, item2dict(ads))


@house.route('/<int:h_id>', methods=['GET'])
@my_cache(10)
def house_info(h_id):
    houses = House.query.get(h_id)
    print(houses)
    ret_house = item2dict(houses)
    ret_house['facility'] = item2dict(houses.facility)
    return my_route(200, ret_house)


@house.route('/facility', methods=['GET'])
def facility():
    return my_route(200, item2dict(Facility.query.all()))


@house.route('/', methods=['GET'])
def get_houses():
    request.data
    data = dict(request.args)
    order = data.pop('order')
    # offset, limit = old_limit(data)

    # houses = House.query.filter_by(live=0, **data) \
    #     .order_by(text(order)) \
    #     .offset(offset).limit(limit).all()

    # 瀑布流分页
    limit = data.pop('limit')
    end_id = int(data.pop('end_id'))

    start_t = int(data.pop('start_t'))
    end_t = int(data.pop('end_t'))

    orders = Order.query.filter(Order.end_t > start_t, Order.end_t <= end_t).all()

    sql = House.query.filter(House.live == 0, House.id.__gt__(end_id)) \
        .filter(*[getattr(House, k) == v for k, v in data.items()])

    for ord in orders:
        sql = sql.filter(House.id != ord.house_id)
    houses = sql.order_by(text(order)).limit(limit).all()

    return my_route(200, item2dict(houses))


@house.route('/comment/<int:h_id>', methods=['GET'])
def get_houses_comment(h_id):
    c_id = request.args.get('c_id')
    sql = Comment.query.filter(Comment.house_id == h_id)
    if c_id:
        sql = sql.filter(Comment.root_id == c_id)
    else:
        sql = sql.filter(Comment.beau == None)

    comments = item2dict(sql.all())

    temp_comments = {v['id']: v for v in comments}
    ret_data = []

    for _, v in temp_comments.items():
        beau = temp_comments.get(v['beau'], None)
        if not beau:
            ret_data.append(v)
        else:
            beau['son'] = beau.get('son', []) + [v]

    return my_route(200, ret_data)


@house.route('/comment/<int:h_id>', methods=['POST'])
def add_houses_comment(h_id):
    data = request.json

    # 评论数加一
    if 'root_id' in data:
        Comment.query.filter_by(id=data['root_id']).update({'num': Comment.num + 1})

    # 加新评论
    db.session.add(Comment(**data))
    db.session.commit()
    return my_route(200)
